"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@umijs/utils");
const inquirer = require("inquirer");
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
const questions_1 = require("../../lib/questions/questions");
const getProjectPackageFile = () => {
    return path_1.join(require('cpaas-webpack-scripts/config/paths').appRootPath, 'package.json');
};
const readProjectPackageJsonDependencies = () => __awaiter(void 0, void 0, void 0, function* () {
    return new Promise((resolve, reject) => {
        let packageFile = getProjectPackageFile();
        fs_extra_1.readFile(packageFile, (error, buffer) => {
            if (error !== undefined && error !== null) {
                reject(error);
            }
            else {
                const obj = JSON.parse(buffer.toString());
                resolve(Object.assign(Object.assign({}, obj.devDependencies), obj.dependencies));
            }
        });
    });
});
const modifyJsonFile = (filePath, modifyHandle) => __awaiter(void 0, void 0, void 0, function* () {
    const jsonData = fs_extra_1.readJSONSync(filePath);
    const newJsonData = yield modifyHandle(jsonData);
    if (newJsonData) {
        fs_extra_1.writeJSONSync(filePath, newJsonData, { spaces: 2 });
    }
});
const getCpaasModules = () => __awaiter(void 0, void 0, void 0, function* () {
    const allCpaasPackageConfig = require('cpaas-webpack-scripts/config/cpaas-packages');
    if (allCpaasPackageConfig.packages) {
        return allCpaasPackageConfig.packages;
    }
    return [];
});
function default_1(api) {
    api.registerCommand({
        name: 'add',
        alias: 'a',
        description: '添加 cpaas 包',
        fn({ args }) {
            return __awaiter(this, void 0, void 0, function* () {
                let cliPackages = args._;
                if (cliPackages[0] === 'a') {
                    cliPackages.shift();
                }
                const currentCpaasDept = yield readProjectPackageJsonDependencies();
                if (cliPackages.length <= 0) {
                    const message = '选择额外的 Cpaas 模块?';
                    const currentCpaasDeptNames = Object.keys(currentCpaasDept);
                    const cpaasModules = (yield getCpaasModules()).filter((item) => !currentCpaasDeptNames.includes(item.name));
                    const checkboxOptions = cpaasModules.map((item) => item.desc ? `${item.name} - [${item.desc}]` : item.name);
                    const defaultOptions = cpaasModules
                        .filter((item) => item.defaultInstall)
                        .map((item) => item.desc ? `${item.name} - [${item.desc}]` : item.name);
                    const questions = [
                        questions_1.generateCheckbox('cpaasPackages')(message)(checkboxOptions)(defaultOptions),
                    ];
                    const prompt = inquirer.createPromptModule();
                    const answers = yield prompt(questions);
                    cliPackages = answers['cpaasPackages'].map((pInfo) => pInfo.replace(/ -.*$/, ''));
                }
                if (cliPackages.length > 0) {
                    const version = (currentCpaasDept['cpaas-front'] || '~1.4.0').replace(/^(([\^~\d]+\.){2}).*$/, '$10');
                    const packageFile = getProjectPackageFile();
                    yield modifyJsonFile(packageFile, (data) => {
                        const newData = utils_1.lodash.cloneDeep(data);
                        let modified = false;
                        cliPackages.forEach((name) => {
                            if (currentCpaasDept[name]) {
                                console.warn(`${name}@${currentCpaasDept[name]} 已存在(${packageFile})`);
                                return;
                            }
                            newData.dependencies[name] = version;
                            modified = true;
                        });
                        if (modified) {
                            console.log(`模块添加完毕 ${cliPackages.join(', ')}, 请执行 yarn install 重新安装依赖`);
                            return newData;
                        }
                        else {
                            return null;
                        }
                    });
                }
            });
        },
    });
    api.registerCommand({
        name: 'upgrade',
        description: '安全升级 cpaas-cli',
        details: `cpaas-cli upgrade`,
        fn({ args }) {
            return __awaiter(this, void 0, void 0, function* () {
                const packageFile = getProjectPackageFile();
                yield modifyJsonFile(packageFile, (data) => {
                    const newData = utils_1.lodash.cloneDeep(data);
                    let modified = false;
                    const currentCpaasDept = Object.assign(Object.assign({}, data.devDependencies), data.dependencies);
                    const currentCpaasFrontVersion = currentCpaasDept['cpaas-front'].replace(/^[\^~](\d+\.\d+)\..*$/, '$1');
                    if (currentCpaasFrontVersion &&
                        currentCpaasFrontVersion !== currentCpaasDept['cpaas-front']) {
                        if (+currentCpaasFrontVersion >= 1.3) {
                            modified = true;
                            delete newData.devDependencies['cpaas-boot'];
                            delete newData.dependencies['cpaas-boot'];
                            delete newData.dependencies['cpaas-cli'];
                            delete newData.dependencies['cpaas-front'];
                            newData.devDependencies['cpaas-cli'] = '~2.1.0';
                            newData.devDependencies['cpaas-front'] = `~${currentCpaasFrontVersion}.0`;
                            newData.resolutions = Object.assign(Object.assign({}, newData.resolutions), { 'eslint': '5.12.0', 'path-to-regexp': '3.2.0', 'mobx': '4.15.7', 'mobx-react': '6.1.4', 'eslint-config-airbnb': '^17.1.0', 'eslint-config-prettier': '^4.0.0', 'eslint-config-react-app': '^3.0.7', 'eslint-plugin-babel': '^5.3.0', 'eslint-plugin-compat': '^3.3.0', 'eslint-plugin-flowtype': '2.50.1', 'eslint-plugin-import': '2.14.0', 'eslint-plugin-jsx-a11y': '6.1.2', 'eslint-plugin-react': '7.12.4', 'stylelint': '13.7.1', 'conventional-changelog': '~3.0.6', 'browserslist': '4.8.5', 'electron-to-chromium': '1.3.473', 'url-loader': '1.1.2', 'css-loader': '1.0.0', 'react-dnd': '^7.0.2', 'react-dnd-html5-backend': '^7.0.2', 'lerna': '3.20.2', 'optimize-css-assets-webpack-plugin': '5.0.3', 'file-loader': '2.0.0', 'mini-css-extract-plugin': '0.4.1', 'less-loader': '5.0.0', 'caniuse-lite': '1.0.30001135', '@babel/cli': '^7.8.4', 'webpack': '4.42.1', 'react': '16.12.0', 'react-router': '4.3.1', 'react-router-dom': '4.3.1', 'react-dom': '16.12.0', 'html-webpack-plugin': '4.0.0-alpha.2', 'typescript': '3.8.2' });
                        }
                        else if (+currentCpaasFrontVersion <= 1.2) {
                            modified = true;
                            delete newData.dependencies['cpaas-boot'];
                            delete newData.dependencies['cpaas-cli'];
                            delete newData.dependencies['cpaas-front'];
                            newData.devDependencies['cpaas-cli'] = `~${currentCpaasFrontVersion}.0`;
                            newData.devDependencies['cpaas-boot'] = `~${currentCpaasFrontVersion}.0`;
                            newData.devDependencies['cpaas-front'] = `~${currentCpaasFrontVersion}.0`;
                            newData.resolutions = Object.assign(Object.assign({}, newData.resolutions), { 'eslint': '5.12.0', 'path-to-regexp': '3.2.0', 'mobx': '4.15.7', 'mobx-react': '6.1.4', 'eslint-config-airbnb': '^17.1.0', 'eslint-config-prettier': '^4.0.0', 'eslint-config-react-app': '^3.0.7', 'eslint-plugin-babel': '^5.3.0', 'eslint-plugin-compat': '^3.3.0', 'eslint-plugin-flowtype': '2.50.1', 'eslint-plugin-import': '2.14.0', 'eslint-plugin-jsx-a11y': '6.1.2', 'eslint-plugin-react': '7.12.4', 'stylelint': '13.7.1', 'conventional-changelog': '~3.0.6', 'browserslist': '4.8.5', 'electron-to-chromium': '1.3.473', 'url-loader': '1.1.2', 'css-loader': '1.0.0', 'react-dnd': '^7.0.2', 'react-dnd-html5-backend': '^7.0.2', 'lerna': '3.20.2', 'optimize-css-assets-webpack-plugin': '5.0.3', 'file-loader': '2.0.0', 'mini-css-extract-plugin': '0.4.1', 'less-loader': '5.0.0', 'caniuse-lite': '1.0.30001135', '@babel/cli': '^7.8.4', 'webpack': '4.42.1', 'react': '16.12.0', 'react-router': '4.3.1', 'react-router-dom': '4.3.1', 'react-dom': '16.12.0', 'html-webpack-plugin': '4.0.0-alpha.2', 'typescript': '3.8.2' });
                        }
                        if (modified) {
                            console.log(`cpaas-cli 升级完成 当前 cpaas-front 版本: ${currentCpaasFrontVersion}\n请执行 yarn install 重新安装依赖`);
                            return newData;
                        }
                        else {
                            console.log(`当前没有更新。`);
                            return null;
                        }
                    }
                });
            });
        },
    });
}
exports.default = default_1;
